package com.iengine.services.api.command.chat;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
/**
 * 简单加减乘除
 * @author Jesen
 *
 */
public class CommandComputer extends AbstractTxtPhoneApiCommand{
	public static final String DIVISION_ERROR = "零不能作为除数，请换个试试";
	public static final String COMPUTER_ERROR = "我还不会算呢，请换个试试";
	
	@Override
	protected Map formatArgs(Map map, Map nlpParams) {
		String oper = getValue(nlpParams.get("Oper"),"");
		String value1 = getValue(nlpParams.get("Value1"),"");
		String value2 = getValue(nlpParams.get("Value2"),"");
		try {
			BigDecimal v1 = new BigDecimal(value1);
			BigDecimal v2 = new BigDecimal(value2);
			if(oper.equals("+")){
				v1 = v1.add(v2);
			}else if(oper.equals("-")){
				v1 = v1.subtract(v2);
			}else if(oper.equals("*")){
				v1 = v1.multiply(v2);
			}else if(oper.equals("/")){
				int r=v2.compareTo(BigDecimal.ZERO);
				if(r == 0){
					throw new Exception("DIVISION_ERROR");
				}
				v1 = v1.divide(v2, 2, RoundingMode.HALF_UP);
			}
			String str = "等于";
			int r=v1.compareTo(BigDecimal.ZERO);
			if(r == 0){
				str += "0";
			}else{
				r=v1.compareTo(BigDecimal.ZERO);
				if(r == -1){
					str += "负";
					v1 = v1.multiply(new BigDecimal(-1));
				}
				str += trim(v1.toString());
			}
			map = addValue(map, isDirectReturn(), str);
		} catch (Exception e) {
			String result = COMPUTER_ERROR;
			if(e.getMessage().equals("DIVISION_ERROR")){
				result = DIVISION_ERROR;
			}
			map = addValue(map, isDirectReturn(), result);
		}
		return map;
	}
	
	public String trim(String str) {
		if (str.indexOf(".") != -1 && str.charAt(str.length() - 1) == '0') {
			return trim(str.substring(0, str.length() - 1));
		} else {
			return str.charAt(str.length() - 1) == '.' ? str.substring(0,
					str.length() - 1) : str;
		}
	}
		
	
	public double addOperate(double v1, double v2){
		return v1+v2;
	}
	
	public double minusOperate(double v1, double v2){
		return v1-v2;
	}
	
	public double multiOperate(double v1, double v2){
		return v1 * v2;
	}
	
	public double divisionOperate(double v1, double v2){
		return v1 / v2;
	}

	public String getPrettyNumber(double number) {  
	    return BigDecimal.valueOf(number).stripTrailingZeros().toPlainString();  
	} 
}
